package com.lx.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.lx.common.constant.ProductConstant;
import com.lx.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.lx.gulimall.product.dao.AttrGroupDao;
import com.lx.gulimall.product.dao.CategoryDao;
import com.lx.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.lx.gulimall.product.entity.AttrGroupEntity;
import com.lx.gulimall.product.entity.CategoryEntity;
import com.lx.gulimall.product.service.CategoryService;
import com.lx.gulimall.product.vo.AttrGroupControllerVo;
import com.lx.gulimall.product.vo.AttrRespVo;
import com.lx.gulimall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lx.common.utils.PageUtils;
import com.lx.common.utils.Query;

import com.lx.gulimall.product.dao.AttrDao;
import com.lx.gulimall.product.entity.AttrEntity;
import com.lx.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        // 保存基本信息
        this.save(attrEntity);
        // 保存关联关系
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationDao.insert(relationEntity);
        }

    }

    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type", "base".equalsIgnoreCase(type)
                        ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                        : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        // 判断分类id是0，是0就查询全部的
        if (catelogId != 0) {
            // 根据传过来的分类id查询
            queryWrapper.eq("catelog_id", catelogId);
        }
        // 查看请求体带来的key值,并且进行sql查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            // 如果key不是空的话 拼sql语句
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id", key).or().like("attr_name", key);
            });
        }

        // 返回分页数据
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        // 封装分页数据
        PageUtils pageUtils = new PageUtils(page);
        // 获取分页数据值
        List<AttrEntity> records = page.getRecords();
        // 再次查询封装到 AttrRespVo 并返回List集合
        List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            // 把attrEntity值复制到attrRespVo里面，属性名必须一样要不然复制不上
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            if ("base".equalsIgnoreCase(type)) {
                // 查询`pms_attr_attrgroup_relation` 属性&属性分组中间表
                AttrAttrgroupRelationEntity attrId = relationDao.selectOne(
                        // 查询
                        new QueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq("attr_id", attrEntity.getAttrId())
                );
                // 查询之后的值不是 null
                if (attrId != null && attrId.getAttrGroupId() != null) {
                    // 查询 属性分组表 `pms_attr_group`
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrId.getAttrGroupId());
                    // 查询的结果分装到attrRespVo里
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }



            // 查询 三级分类表 `pms_category`
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity.getName() != null) {
                // 封装
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            // 返回
            return attrRespVo;
        }).collect(Collectors.toList()); // 转换成List集合
        // 替换pageUtils原来的List
        pageUtils.setList(respVos);
        return pageUtils;
    }

    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);


        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 1.设置分组信息
            AttrAttrgroupRelationEntity attrgroupRelation = relationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq("attr_id", attrEntity.getAttrId())
            );
            if (attrgroupRelation.getAttrGroupId() != null) {
                attrRespVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupRelation.getAttrGroupId());
                if (attrGroupEntity.getAttrGroupName() != null) {
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        // 设置三级分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRespVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity.getName() != null) {
            attrRespVo.setGroupName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Transactional
    @Override
    public void updateByIdAttr(AttrVo attr) {

        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            Integer count = relationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId())
            );

            if (count > 0) {
                relationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId())
                );
            } else {
                relationDao.insert(relationEntity);
            }
        }


    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        // 通过attrGroupId查询中间表对象的属性
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelation = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_group_id", attrGroupId)
        );
        List<Long> collect = attrAttrgroupRelation.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        if (collect == null || collect.size() == 0) {
            return null;
        }
        Collection<AttrEntity> attrEntities = this.listByIds(collect);
        return (List<AttrEntity>) attrEntities;
    }

    @Override
    public void deleteRelation(AttrGroupControllerVo[] vos) {
        List<AttrAttrgroupRelationEntity> collect = Arrays.asList(vos).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrgroupRelationEntity);
            return attrgroupRelationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(collect);
    }

    /**
     * 获取当前属性没有关联的所有属性
     *
     * @param params
     * @param attrGroupId
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        // 1.当前分组只能关联自己所属的分类的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        // 获取当前属性分组的三级分类的id
        Long catelogId = attrGroupEntity.getCatelogId();

        // 查询属性组 条件是同一个三级分类
        List<AttrGroupEntity> attrGroupEntityList = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", catelogId)
                // 这里是否需要过滤当前属性组的id 查询attrGroupId属性组的其他属性
                        //.ne("attr_group_id", attrGroupId)
        );

        // 获取属性组里面的其他属性组id
        List<Long> attrGroupIdList = attrGroupEntityList.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        // 根据三级分类id和类型 查询 属性表
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                );
        // 然后查询出已有当前的属性分组&属性中间表
        List<AttrAttrgroupRelationEntity> attrGroupRelationEntityList = relationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", attrGroupIdList)
        );
        // 遍历出属性分组&属性 中间表已有的属性id
        List<Long> attrId = attrGroupRelationEntityList.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        if (attrId != null && attrId.size() > 0) {
            wrapper.notIn("attr_id", attrId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w)->{
                w.eq("attr_id", key)
                        .or()
                        .like("attr_name", key);
            });

        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIdList) {
        /**
         * SELECT attr_id FROM `pms_attr` WHERE attr_id IN(?) AND search_type = 1
         */
        return this.baseMapper.selectSearchAttrs(attrIdList);
    }

}